from pathlib import Path

import sqlite3
from conf.settings import logger

def get_db_tables(db_path) -> list:
    """
    获取数据库中所有表
    :param db_path: 数据库文件路径
    :return: 包含表名的列表
    """
    tables = []
    db_path = Path(db_path)

    try:
        with sqlite3.connect(db_path) as conn:
            cursor = conn.cursor()
            # 直接查询sqlite_master表获取所有表名
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
            tables = cursor.fetchall()
    except sqlite3.Error as e:
        logger.warning(f'数据库访问失败，错误：{e}')
    except Exception as e:
        logger.error(f'未预期的错误发生：{e}')
    except BaseException:
        logger.info("操作被终止")

    ret = [tbl[0] for tbl in tables]
    logger.info(f'数据库中包含 {len(ret)} 张表')
    return ret

def alter_path(file_path, head: str = '', tail: str = '', suffix: str = ''):
    file_path = Path(file_path)
    new_path = file_path.parent / f'{head}{file_path.stem}{tail}{suffix or file_path.suffix}'
    return new_path


if __name__ == '__main__':
    BASE_DIR = Path(__file__).resolve().parent.parent
    db_path = BASE_DIR / 'to_be_checked/db_files/current/iAppsSupport/NewTable/MFCONFIG_bak.db'
    # out_dir = BASE_DIR / 'temp'
    #
    # db_to_csv(db_path, out_dir)

    print(alter_path('/Users/xiaofo/CodeBase/DBTranslator/data/temp/MFCONFIG_bak.db#TBL_CF_NEW_APPNAME_2_BCPCODE.csv',
                tail='_two',
               head='new_',
               suffix='.txt'))
